package com.topboya.officeuser.controller.parse.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @className OperateExcelUtils
 * @Author xiaxin
 * @Date 2020/12/31 16:19
 * @Version 1.0
 **/
public class OperateExcelUtils {
    public List<List<String>> readList(MultipartFile multipartFile) throws IOException {
        Workbook wb = new XSSFWorkbook(multipartFile.getInputStream());
        Sheet sheet = wb.getSheetAt(0);
        int rows = sheet.getPhysicalNumberOfRows();

        List<List<String>> list = new ArrayList<>();
        for (int i=0;i<rows;i++){
            List<String> stringList = new ArrayList<>();
            Row row = sheet.getRow(i);
            if(row!=null) {
                int cells = row.getLastCellNum();
                for (int j = 0; j < cells; j++) {
                    String cell = "";
                    Cell cell1 = row.getCell(j);
                    if(cell1==null) {
                        
                            cell = "";
                    }else {
                        cell = cell1.toString();
                    }
                    stringList.add(cell);
                }
                list.add(stringList);
            }
        }
        return list;
    }

    public  void WriteList(List<List<String>> successList, String path) throws IOException {

        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet();
        List<String> strings = successList.get(0);
        int r = strings.size();

        for(int i = 0;i<successList.size();i++){
            Row row = sheet.createRow(i);
            List<String> strings1 = successList.get(i);
            for(int j = 0; j<r;j++){
                Cell cell = row.createCell(j);
                cell.setCellValue(strings1.get(j));
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(path);
        wb.write(fileOutputStream);
    }

}
